import api from '../../request/api.js';
import toast from '../../miniprogram_npm/@vant/weapp/toast/toast.js';
Page({

  data: {
    addressInfo:[],
    type:'',
  },
  chooseAdr(e){
    const { address} = e.currentTarget.dataset
    const {type} = this.data
    if(type){
      wx.setStorageSync('orderAddress', address)
      if(type == 'shop'){
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];  //上一个页面
        prevPage.setData({
          address_id : address.address_id,
          type: 'address'
        })
      }
      wx.navigateBack({
        delta: 1,
        success: (res) => {
          this.setData({
            type:''
          }) 
        }, 
      })
    }
  },
  async deletAddress(e){
    let id = e.currentTarget.dataset.id
    console.log(id)
    console.log('delete')
    const res = await api('POST', 'Recycle/address/deleteAddress', {
      token: wx.getStorageSync('token'),
      address_id:id
    })
    if (res.data.code === 200) {
     let newaddress =  this.data.addressInfo.filter(item => {
        return item.address_id !== id
      })
      this.setData({
        addressInfo: newaddress
      })
    }
  },
  async getAddressList(){
    const res = await api('GET', 'Recycle/address/getAllAddress', {
      token: wx.getStorageSync('token')
    })
    if(res.data.code===200){
      this.setData({
        addressInfo: res.data.data
      })
    }
  },
  editAddress(e){
    let id = e.target.id
    this.data.addressInfo.forEach(i => {
      if (id == i.address_id){
        wx.setStorageSync('editAddress', i)
      }
    })
    wx.navigateTo({
      url: '../newAddress/index?id='+id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //兑换商品
    if(options.type == 'shop'){
      wx.setNavigationBarTitle({
        title: '地址选择' 
      })
    }
    this.setData({
      type:options.type
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.getAddressList()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAddressList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})